var PATH_PREFIX ="";

var currentTabType = ''; 

function setPathPrefix(path){
	PATH_PREFIX =  path;
}

$(function() {
	// 给select2组件加载样式
	WASP_WIDGET.initializeSelectStyle();
	// 注册清空事件
    WASP_WIDGET.registerResetClearEvent();
    
    WASP_WIDGET.triggerSelectOnEmpId("#q-uploader", {queryDimission : true,cleanDele: true});
    WASP_WIDGET.triggerSelectOnEmpId("#q-confirmer", {queryDimission : true,cleanDele: true});
    WASP_WIDGET.triggerDateRangeStyle("q-uploadTime");
    WASP_WIDGET.triggerDateRangeStyle("q-confirmTime");
    WASP_WIDGET.triggerDateRangeStyle("q-todoDate");
    
    TODO_OUTPUT.init();
    
    // 定时刷新数据
    /*setInterval(function(){
    	TODO_OUTPUT.initTodoView();
	}, 10000);*/
});



var TODO_OUTPUT = {
	init: function () {
		this.$resultBox = $('.result-box');
		this.$resultBox.height(document.body.scrollHeight - 180);
		
		this.initTodoView();
		this.bind();
	},
	bind: function () {
		this.$resultBox.on('click', '.product-list-group p.on,.product-list-group p.off', $.proxy(this.contactCtr, this));
		this.$resultBox.on('click', '#pageTabs li', $.proxy(this.tabChange, this));
		this.$resultBox.on('click', '.show-all', $.proxy(this.showAll, this));
		this.$resultBox.on('click', '.alert-box i.fa-times', $.proxy(this.closeAlertBox, this));
	},
	//关闭弹出框
	closeAlertBox: function (e) {
		var $this = $(e.currentTarget);
		$('.bg').remove();
		$('.alert-box').remove();
	},
	//展示全部
	showAll: function (e) {
		var $this = $(e.currentTarget);
		var data = this.defaultData;
		var serviceType = $('#pageTabs').find('li.active').data('type');
		var type = $this.data('type');
		var view = '';
		$.each(data.object, function (i, k) {
			if (this.serviceType == serviceType) {
				view = this[type];
			}
		});
		var d = {result: view};
		var $tpl = $('#template2').html();
		if ($this.prev().hasClass('blue')) {
			$tpl = $('#template3').html();
		}
		
		var viewDom = Mustache.render($tpl, d);
		layer.open({
		  title: '全部待办',
	      type: 1,
	      area: ['580px', '400px'], // 设置宽度，高度
	      shadeClose: true, //点击遮罩关闭
	      content: viewDom,
	      isOutAnim: false,
	      resize: false
	    });
		
		// 瀑布流布局
		var $container = $('.masonry-container');
		$container.masonry({
			columnWidth: '.masonry-item',
			itemSelector: '.masonry-item'
		});
	},
	//左侧tab切换
	tabChange: function (e) {
		var $this = $(e.currentTarget);
		var index = $this.index();
		$this.addClass('active').siblings().removeClass('active');
		
		currentTabType = $this.data("type");
		
		$('.panel-solution').eq(index).show().siblings().hide();
		var height = $('#overView').height();
		if (height > this.$defaultOverviewTabsHeight) {
			$('.overview-tabs').height(height);
		}else {
			$('.overview-tabs').height(this.$defaultOverviewTabsHeight);
		}
		
	},
	//展开收起联系经办人员
	contactCtr: function (e) {
		var $this = $(e.currentTarget);
		if ($this.hasClass('on')) {
			$this.removeClass('on').addClass('off');
			$this.prev().hide();
			$this.prev().prev().hide();
			$this.children('span').html('联系经办人员');
			$this.children('i.fa-caret-up').removeClass('fa-caret-up').addClass('fa-caret-down');
		}else {
			$this.removeClass('off').addClass('on');
			$this.prev().show();
			$this.prev().prev().show();
			$this.children('span').html('收起');
			$this.children('i.fa-caret-down').removeClass('fa-caret-down').addClass('fa-caret-up');
		}
	},
	tabActive: function(element) {
		$('.tab').removeClass("active");
		if(element != null){
			$('#'+element + "Btn").addClass('active');
		}
		
		$('.tabContainer').hide();
		$('#'+element).show();
		
		if(element == "calendarViewTab") {
			showCalendar();
		} else {
			jqGridResize($('#todoList'), $("#listViewTab"));
		}
	},
	
	// 初始化待办数据
	initTodoView: function() {
		var that = this;
		$.ajax({
			type : "GET",
			dataType : "json",
			url : PATH_PREFIX + 'getOverviewData.do',
			cache: false,
			data: {
				
			},
			success: function(data) {
				if (data.success) {
					that.defaultData = data;
					// 初始化到页面上
					var allTodoCount = 0;
					var initData = JSON.parse(JSON.stringify(data.object));
					$.each(initData, function(i, data) {
						data.toUploadCount = data.toUploadList.length;
						data.toConfirmCount = data.toConfirmList.length;
						data.toProcessCount = data.toProcessList.length;
						data.complateCount = data.complateList.length;
						data.totalCount = data.toUploadCount + data.toConfirmCount + data.toProcessCount + data.complateCount;
						allTodoCount += data.totalCount;
						if (data.totalCount == 0) {
							data.totalCount = '';
						}
						data.toUploadListLengthFlag = false;
						if (data.toUploadCount > 5) {
							data.toUploadList = data.toUploadList.slice(0, 5);
							data.toUploadListLengthFlag = true;
						}
						data.toConfirmListLengthFlag = false;
						if (data.toConfirmCount > 5) {
							data.toConfirmList = data.toConfirmList.slice(0, 5);
							data.toConfirmListLengthFlag = true;
						}
						data.toProcessListLengthFlag = false;
						if (data.toProcessCount > 5) {
							data.toProcessList = data.toProcessList.slice(0, 5);
							data.toProcessListLengthFlag = true;
						}
						data.complateListLengthFlag = false;
						if (data.complateCount > 5) {
							data.complateList = data.complateList.slice(0, 5);
							data.complateListLengthFlag = true;
						}
						$.each(data.toUploadList, function () {
							this['exclamation'] = false;
							if (this.status == 'R') {
								this.exclamation = true;
							};
						});
					});

					var d = {result: initData};
					var $tpl = $('#template1').html();
					$('#pageTabs').html(Mustache.render($tpl, d));
					that.$defaultOverviewTabsHeight = $('.overview-tabs').height();
					
					var view = {
						result: initData
					}
					var $tpl = $('#modulTemplate').html();
				    $('#overView').html(Mustache.render($tpl, view));
				    
				    if(currentTabType) {
				    	$('#pageTabs').find('li[data-type="' + currentTabType + '"]').click();
				    } else {
				    	$('#pageTabs').find('li:first').click();
				    }
					
					$.each(data.object, function(i, data) {
						if (!data.complateCount) {
							$("#download_" + data.serviceType).attr("disabled", "disabled");
						}
					});
					
					// 刷新“我的”数值
					if(allTodoCount) {
						$(".my-circle").show();
						
						var count = allTodoCount * 1;
						if(count > 99) {
							$(".my-circle").html("99+");
						} else {
							$(".my-circle").html(count);
						}
						
					} else {
						$(".my-circle").hide();
					}
				}
			}
		});
	},
	
	fileDetail: function(id) {
		window.open(PATH_PREFIX + "fileDetailView.do?id=" + id);
	},
	
	fileUpload: function(id) {
		window.open(PATH_PREFIX + "todoFileUploadView.do?id=" + id);
	},
	
	noFileUpload: function(id) {
		var confirmIndex = layer.confirm('确认无需上传？', {
			btn: ['确认','取消'] //按钮
		}, function(){
			$.ajax({
				type : "POST",
				dataType : "json",
				url : PATH_PREFIX + "noFileUpload.do",
				cache: false,
				data: {
					id: id
				},
				success: function(data) {
					if (data.success) {
						layer.msg();
						ctools.alert(data.message, "", "success");
					} else {
						layer.msg(data.message);
						ctools.alert(data.message, "", "warning");
					}
					queryByCondtion(false);
					// 刷新列表
					$uploadTodoList.jqGrid("setGridParam",{"datatype": "json"}).trigger("reloadGrid", [{ page: 1 }]); //重新载入Grid表格
				},
				error:function(xhr){
				   sweetAlertAjaxError(xhr);
				}
			});
			
			layer.close(confirmIndex);
			
		}, function(){
			
		});
	},
	
	fileConfirm: function(id) {
		window.open(PATH_PREFIX + "todoFileConfirmView.do?id=" + id);
	},
	
	fileEnd: function(id) {
		window.open(PATH_PREFIX + "fileEndView.do?id=" + id);
	},
	
	addView: function() {
		window.open(PATH_PREFIX + "addView.do");
	},
	
	listFileUpload: function(todoType) {
		$("#q-todoType").val(todoType).trigger("change");
		$("#q-todoDate").val(moment().format('YYYY/MM/DD') + " - " + moment().format('YYYY/MM/DD'));
		TODO_OUTPUT.tabActive('listViewTab');
		queryByCondtion(true);
	},
	
	downloadTodyOutput: function(serviceType) {
		layer.open({
			  type: 2,
			  title: '下载产出',
			  shadeClose: true,
			  isOutAnim: false,
			  shade: 0.5,
			  area: ['800px', '320px'],
			  content: PATH_PREFIX + 'outDownloadView.do?serviceType=' + serviceType //iframe的url
		});
	},
	
	openFileUpload: function(serviceType) {
		// 加载对应待办待上传的数据
		$.get(PATH_PREFIX + 'toUploadListView.do', {serviceType: serviceType}, function(result){
//	    	// 弹出显示
			layer.open({
			  title: '材料上传',
		      type: 1,
		      area: ['800px', '470px'], // 设置宽度，高度
		      maxHeight: 600, // 最大高度
		      shadeClose: true, //点击遮罩关闭
		      isOutAnim: false,
		      content: result,
		      resize: false
		    });
		});
	},
	
	deleteTodo: function(id) {
		var confirmIndex = layer.confirm('确认删除？', {
			btn: ['确认','取消'] //按钮
		}, function(){
			$.ajax({
				type : "POST",
				dataType : "json",
				url : PATH_PREFIX + "deleteTodo.do",
				cache: false,
				data: {
					id: id
				},
				success: function(data) {
					if (data.success) {
						ctools.alert(data.message, "", "success");
					} else {
						ctools.alert(data.message, "", "warning");
					}
					queryByCondtion(false);
					// 刷新列表
					$uploadTodoList.jqGrid("setGridParam",{"datatype": "json"}).trigger("reloadGrid", [{ page: 1 }]); //重新载入Grid表格
				},
				error:function(xhr){
				   sweetAlertAjaxError(xhr);
				}
			});
			
			layer.close(confirmIndex);
			
		}, function(){
			
		});
	}
};


//post 提交下载表单
function post(url, params) {
	var temp_form = document.createElement("form");      
	temp_form.action = url;
	temp_form.target = "_self";
	temp_form.method = "post";
	temp_form.style.display = "none";
	for (var x in params) {
		var opt = document.createElement("input");
	    opt.name = x;
	    opt.value = params[x];
	    temp_form.appendChild(opt);
	}
	document.body.appendChild(temp_form);
	temp_form.submit();
}



var $todoList = $('#todoList');
var $uploadTodoList = $('#uploadTodoList');

var $gridparents = $("#listViewTab");//基于哪个父级元素使jqgrid自适应宽度，主要解决tab标签切换隐藏的列表宽度不对的问题
$(function() {
	// 我的待办明细
	$todoList.jqGrid({
		url:PATH_PREFIX + 'todoListPage.do',    
		datatype: "json",
		colNames:["id","管理人", "服务类型", "待办类型","待办日期","产品简称","产品代码","status", "状态", "上传人", "上传时间", "确认人", "确认时间", "完成人", "完成时间", "操作"],        
		colModel:[  { name: 'id', index: 'id', key: true, hidden:true },       
		            { name: 'companyName', index: 'companyName', width: '130px', resizable: true, sortable: false, hidden:true },
		            { name: 'serviceTypeName', index: 'serviceTypeName', width: '130px', resizable: true, sortable: false },
		            { name: 'todoTypeName', index: 'todoTypeName', width: '140px', resizable: true, sortable: false },
		            { name: 'todoDate', index: 'todoDate', width: '125px', resizable: true, sortable: false },
		            { name: 'prjSname', index: 'prjSname', width: '125px', resizable: true, sortable: false },
		            { name: 'outerId', index: 'outerId', width: '125px', resizable: true, sortable: false },
		            { name: 'status', index: 'status', hidden:true },
		            { name: 'statusNm', index: 'statusNm', width: '125px', resizable: true, sortable: false },
		            { name: 'uploaderName', index: 'uploader', width: '130px', resizable: true, sortable: false, hidden:true },
		            { name: 'uploadTime', index: 'uploadTime', width: '140px', resizable: true, sortable: false },
		            { name: 'confirmerName', index: 'confirmer', width: '130px', resizable: true, sortable: false, hidden:true },
		            { name: 'confirmTime', index: 'confirmTime', width: '140px', resizable: true, sortable: false },
		            { name: 'endName', index: 'endName', width: '130px', resizable: true, sortable: false, hidden:true },
		            { name: 'endTime', index: 'endTime', width: '140px', resizable: true, sortable: false },
		            { name: 'option', index: 'option', width: '350px', resizable: true, sortable: false }
				  ],
		rowNum: 20,
        rowList: [20, 30, 50],
        rownumbers: true,
        rownumWidth: 50,
        prmNames: { search: "search", page: "pageNo", rows: "limit" },
        height: 'auto',
        width: false,
        autowidth:false,
        editurl: '',
        viewrecords: true,
        cellEdit: false,
        shrinkToFit: false,
        grouping: false,
        jsonReader: {
            root: "items", //结果集
            records: "total", //总记录数 
            total: "pageCount", //总页数
            page: "pageNo", //当前页 
            repeatitems: false // (4) 
        },  
		multiselect:false,
		pager: "#todoListPage",						
		viewrecords: true,
		hidegrid: false, 
		gridComplete: function(){
			var ids = $todoList.jqGrid('getDataIDs');
			for(var i = 0;i < ids.length;i++){
				var rowId = ids[i];
				var rowData = $todoList.jqGrid('getRowData', rowId);
				
				var params = {
					'fileDetail' : 'fileDetailTemp',
					'fileUpload' : 'fileUploadTemp',
					'noFileUpload' : 'noFileUploadTemp',
					'fileConfirm': 'fileConfirmTemp',
					'fileEnd'    : 'fileEndTemp',
					'deleteTodo'    : 'deleteTodoTemp'
				};
				var permissionButton = Permission_Button.configPermissionButton(params);
				permissionButton.fileDetail   = Permission_Button.clickPermissionButton('fileDetailTemp',"TODO_OUTPUT.fileDetail('" + rowId + "');");
				if (rowData.status == 'I' || rowData.status == 'R') {
					permissionButton.fileUpload   = Permission_Button.clickPermissionButton('fileUploadTemp',"TODO_OUTPUT.fileUpload('" + rowId + "');");
					permissionButton.noFileUpload   = Permission_Button.clickPermissionButton('noFileUploadTemp',"TODO_OUTPUT.noFileUpload('" + rowId + "');");
				}
				if (rowData.status == 'S') {
					permissionButton.fileConfirm   = Permission_Button.clickPermissionButton('fileConfirmTemp',"TODO_OUTPUT.fileConfirm('" + rowId + "');");
				}
				if (rowData.status == 'C') {
					// 完成
					permissionButton.fileEnd   = Permission_Button.clickPermissionButton('fileEndTemp',"TODO_OUTPUT.fileEnd('" + rowId + "');");
					// 上传产出
//					permissionButton.uploadEndFile   = Permission_Button.clickPermissionButton('uploadEndFileTemp',"TODO_OUTPUT.uploadEndFile('" + rowId + "');");
				}
				
				permissionButton.deleteTodo   = Permission_Button.clickPermissionButton('deleteTodoTemp',"TODO_OUTPUT.deleteTodo('" + rowId + "');");
				
				
				
				$todoList.jqGrid('setRowData', ids[i], { option: Permission_Button.linkAllBtn(permissionButton)});
			}
		}
	});
	$todoList.navGrid('#todoListPage',{edit:false,add:false,del:false,search:false,refreshstate:'current'});
	$todoList.jqGrid('setFrozenColumns');
	jqGridResize($todoList, $gridparents);
});

//绑定回车事件,查询
$("body").keypress(function(event){
	var key = event.which;
	if(key == "13"){
		queryByCondtion(true);
	}
});

function queryByCondtion(flag) {
	var todoType = $("#q-todoType").val();
	var status = $("#q-status").val();
    var todoDateBgn = $("#q-todoDate").getDateRangeValue()[0];
    var todoDateEnd = $("#q-todoDate").getDateRangeValue()[1];
	var prdName = $.trim($("#q-prdName").val());
	var uploader = $("#q-uploader").val();
    var uploadTimeBgn = $("#q-uploadTime").getDateRangeValue()[0];
    var uploadTimeEnd = $("#q-uploadTime").getDateRangeValue()[1];
	var confirmer = $("#q-confirmer").val();
	var confirmTimeBgn = $("#q-confirmTime").getDateRangeValue()[0];
	var confirmTimeEnd = $("#q-confirmTime").getDateRangeValue()[1];
    
    var postData = $todoList.jqGrid("getGridParam", "postData");
    $.extend(postData, {
        'sp[todoType]':todoType,
        'sp[status]':status,
        'sp[todoDateBgn]':todoDateBgn,
        'sp[todoDateEnd]':todoDateEnd,
        'sp[prdName]':prdName,
        'sp[uploader]':uploader,
        'sp[uploadTimeBgn]':uploadTimeBgn,
        'sp[uploadTimeEnd]':uploadTimeEnd,
        'sp[confirmer]':confirmer,
        'sp[confirmTimeBgn]':confirmTimeBgn,
        'sp[confirmTimeEnd]':confirmTimeEnd
    });
    if (flag) {
    	$todoList.jqGrid("setGridParam",{"datatype": "json"}).trigger("reloadGrid", [{ page: 1 }]); //重新载入Grid表格
    } else {
    	$todoList.jqGrid("setGridParam",{"datatype": "json"}).trigger("reloadGrid"); //重新载入Grid表格
    }
    
    TODO_OUTPUT.initTodoView();
    // 关闭弹出框
    layer.closeAll();
};